﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web;

namespace Pcb.Common
{
    public class _Utility
    {
        #region 指定错误页面

        /// <summary>
        /// 跳转到自定义错误页(指定到系统繁忙页)
        /// </summary>
        public static void GoError()
        {
            GoError("系统繁忙，请稍候访问！");
        }

        /// <summary>
        /// 跳转到自定义错误页
        /// </summary>
        /// <param name="errormsg"></param>
        public static void GoError(string errormsg)
        {
            System.Web.HttpContext.Current.Response.Redirect("~/error.aspx?errormsg=" + System.Web.HttpUtility.UrlEncode(errormsg));
        }

        #endregion

        #region IP|Url地址有关

        /// <summary>
        /// 获取发起请求者IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIp()
        {
            return System.Web.HttpContext.Current.Request.UserHostAddress;
        }

        /// <summary>
        /// 获取当前页面URL值
        /// </summary>        
        public static string GetUrl()
        {
            return GetUrl(UrlTypeEnum.Url);

            //如果测试的url地址是http://www.test.com/testweb/default.aspx, 结果如下：

            //HttpContext.Current.Request.Url.PathAndQuery;     // 获取Url中？后面的字符串
            //Request.ApplicationPath:                          // testweb
            //Request.CurrentExecutionFilePath:                 // testweb/default.aspx
            //Request.FilePath:                                 // testweb/default.aspx
            //Request.Path:                                     // testweb/default.aspx
            //Request.PhysicalApplicationPath:                  // E:\WWW\testwebRequest.PhysicalPath:                  
            //Request.RawUrl:                                   // testweb/default.aspx
            //Request.Url.AbsolutePath:                         // testweb/default.aspx
            //Request.Url.AbsoluteUrl:                          // http://www.test.com/testweb/default.aspx
            //Request.Url.Host:                                 // www.test.com
            //Request.Url.LocalPath:                            // /testweb/default.aspx           
        }

        /// <summary>
        /// 获取当前页面URL值
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetUrl(UrlTypeEnum type)
        {
            var typeName = type.ToString();
            string url = HttpContext.Current.Request.Url.ToString();

            switch (typeName)
            {
                case "Url":
                    url = HttpContext.Current.Request.Url.ToString();
                    break;
                case "Host":
                    url = HttpContext.Current.Request.Url.Host;
                    break;
                case "LocalPath":
                    url = HttpContext.Current.Request.Url.LocalPath;
                    break;
                case "PhysicalApplicationPath":
                    url = HttpContext.Current.Request.PhysicalApplicationPath.ToString();
                    break;
                case "ApplicationPath":
                    url = HttpContext.Current.Request.ApplicationPath.ToString();
                    break;
            }

            return url;
        }

        /// <summary>
        /// 返回url类型枚举
        /// </summary>
        public enum UrlTypeEnum
        {
            /// <summary>
            /// 如：返回 http://www.test.com/testweb/default.aspx
            /// </summary>
            Url = 1,

            /// <summary>
            /// 如：返回 www.test.com
            /// </summary>
            Host = 2,

            /// <summary>
            /// 如：返回 /testweb/default.aspx
            /// </summary>
            LocalPath = 3,

            /// <summary>
            /// 如：返回 E:\WWW\testwebRequest.PhysicalPath
            /// </summary>
            PhysicalApplicationPath = 4,

            /// <summary>
            /// 如：返回 testweb
            /// </summary>
            ApplicationPath = 5,

        }

        /// <summary>
        /// WebRequest方式判断某url是否存在
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool UrlExistsUsingHttpWebRequest(string url)
        {
            try
            {
                var myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                myRequest.Method = "HEAD";
                myRequest.Timeout = 10000;
                var res = (System.Net.HttpWebResponse)myRequest.GetResponse();
                return (res.StatusCode == System.Net.HttpStatusCode.OK);
            }
            catch (System.Net.WebException we)
            {
                System.Diagnostics.Trace.Write(we.Message);
                return false;
            }
        }

        #endregion
        
        /// <summary>
        /// 返回web应用程序根目录路径 
        /// <remarks>
        /// 不包含bin目录
        /// </remarks>
        /// </summary>
        public static string GetWebApplicationRootPath()
        {            
            return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;            
        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (strPath.ToLower().StartsWith("http://"))
            {
                return strPath;
            }
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        /// <summary>
        /// 拆分整串为字符串数据
        /// </summary>
        /// <param name="str"> 原串(12,14,13,15....) </param>
        /// <param name="sign"> 拆分字符(',' '|'...) </param>
        /// <returns></returns>
        public static string[] GetStringBySplit(string str, char sign)
        {
            if (str == "")
                return null;

            try
            {
                //if (str.Substring(0, 1) == @sign.ToString())  // 去掉最前面的字符
                //{
                //    str = str.Substring(1, str.Length - 1);
                //}
                if (str.Substring(str.Length - 1, 1) == sign.ToString()) // 去掉最后面的字符
                {
                    str = str.Substring(0, str.Length - 1);
                }
            }
            catch { }

            return str.Split(sign);
        }

        /// <summary>
        /// 获取总页数
        /// </summary>
        /// <param name="pagesize"> 每页显示多少 </param>
        /// <param name="total"> 总记录数 </param>
        /// <returns></returns>
        public static int GetPageAll(int pagesize, int total)
        {
            return ((total % pagesize == 0) ? (total / pagesize) : (total / pagesize + 1));
        }
       
        /// <summary>
        /// 取config下的appsetting中的内容
        /// </summary>
        public static string GetConfigAppSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        /// <summary>
        /// 从一路径中获取文件名(如:lxwapct05/act/movie/1706/27000012.jar 得到 27000012.jar)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetFileNameByPath(string path)
        {
            string filename = "";

            int start = path.LastIndexOf('/');
            int end = path.Length;
            int startIndex = start + 1;
            int length = end - startIndex;

            filename = path.Substring(startIndex, length);

            return filename;
        }

        /// <summary>
        /// 从一路径中获取文件扩展名(如:lxwapct05/act/movie/1706/27000012.jar 得到 jar)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetFileExtByPath(string path)
        {
            path = path.Substring(path.LastIndexOf("."), path.Length - path.LastIndexOf("."));
            string ext = "";

            if (path == "")
                return ext;

            Match match = Regex.Match(path, @"\.[^][0-9][a-zA-Z]+");
            if (match.Value != "")
                ext = match.Value.Replace(".", "");

            return ext;
        }

        /// <summary>
        /// 由字节转换成KB,MB,GB
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string ConvertSize(int size)
        {
            float kb = 0;
            kb = size / 1024;
            if (kb < 1024)
                return (Convert.ToInt32(kb).ToString() + "KB");

            float mb = 0;
            mb = kb / 1024;
            if (mb < 1024)
                return Convert.ToInt32(mb * 10) / 10.0 + "MB";

            float gb = 0;
            gb = mb / 1024;
            return Convert.ToInt32(gb * 10) / 10.0 + "GB";
        }

        /// <summary>
        /// 冒泡排序
        /// </summary>
        /// <param name="str"> 需要排序的字符串数组 </param>
        /// <param name="sortStr"> 排序数 </param>
        /// <returns></returns>
        public static string[] BubbleSort(string[] str, string[] sortStr)
        {
            int length = str.Length;             // 数给长度        

            int t = 0;
            string t_str = "";
            for (int i = 0; i < length - 1; i++)
            {
                for (int j = 0; j < length - i - 1; j++)
                {
                    // 增序排列
                    if (_Convert.ToInt(sortStr[j], 0) > _Convert.ToInt(sortStr[j + 1], 0))
                    {
                        t = _Convert.ToInt(sortStr[j], 0);
                        sortStr[j] = sortStr[j + 1];
                        sortStr[j + 1] = t.ToString();

                        t_str = str[j];
                        str[j] = str[j + 1];
                        str[j + 1] = t_str;
                    }
                }
            }

            return str;
        }

        #region 类型转换

        /// <summary>
        /// 字符串转换为时间类型
        /// </summary>
        /// <param name="Value"> 需要转换的字符串 </param>
        /// <param name="DefaultValue"> 默认值 </param>
        /// <returns> 时间值 </returns>
        public static DateTime StrToDateTime(string Value, DateTime DefaultValue)
        {
            DateTime Result = DefaultValue;

            try
            {
                Result = Convert.ToDateTime(Value);
            }
            catch { }

            return Result;
        }

        #endregion

        #region 正则有关

        /// <summary>
        /// 查询出str字符串中，出现过多少次sign子串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public static int Regex_GetFindFrequency(string str, string sign)
        {
            int num = 0;      // 出现0次

            MatchCollection mc = Regex.Matches(str, sign.ToString(), RegexOptions.None);

            foreach (Match m in mc)
            {
                num++;
            }

            return num;
        }

        /// <summary>
        /// 取出字符串中的数字
        /// </summary>
        /// <returns></returns> 
        public static int Regex_GetNumToString(string str)
        {
            Match m = Regex.Match(str, @"\d");
            int num = _Convert.ToInt(m.Value, 0);

            return num;
        }

        /// <summary>
        /// str字符串中，是否存在(regex)该正则的内容
        /// </summary>
        public static bool Regex_IsContains(string str, string regex)
        {
            bool flag = false;

            MatchCollection mc = Regex.Matches(str, regex, RegexOptions.None);

            foreach (Match m in mc)
            {
                flag = true;
                break;
            }

            return flag;
        }

        #endregion

        #region 首页有关

        /// <summary>
        /// 释放缓存首页,初始化首页 
        /// </summary>
        /// <param name="classid"> 1 软件 2 游戏 </param>
        public static void IndexpageReset(int classid)
        {
            string url = "";

            if (classid == 1)
                url = "http://soft.lexun.com/page/admin/page_item_reset.aspx?opflag=1";
            else if (classid == 2)
                url = "http://game.lexun.com/page/admin/page_item_reset.aspx?opflag=1";

            // 释放缓存首页,初始化首页             
            if (url != "")
            {
                try
                {
                    WebClient wc = new WebClient();
                    wc.Credentials = CredentialCache.DefaultCredentials;
                    wc.DownloadData("");
                }
                catch { }
            }
        }

        #endregion

        #region 网络有关

        /// <summary>
        /// 远程获取文件大小
        /// </summary>
        /// <param name="geturl"> 远程文件地址 </param>
        /// <returns>kb</returns>
        public static int Net_GetFileSize(string geturl)
        {
            int length = 0;

            try
            {
                WebRequest request = WebRequest.Create(geturl);
                WebResponse response = request.GetResponse();
                length = _Convert.ToInt(response.ContentLength.ToString());
            }
            catch { }

            return length;
        }

        #endregion
    }

}
